package utils

import (
	// "encoding/json"
	"strings"
	"fmt"

	apc "github.com/ChrisMuir/address-parse-china"
)

var CityName = "绥化市"

var Counties= []string{
    "绥化市",
    "北林区",
    "肇东市",
    "安达市",
    "海伦市",
    "兰西县",
    "庆安县",
    "绥棱县",
    "望奎县",
	"明水县",
    "青冈县",
}

var CountyMap = func() map[string]int {
    m := make(map[string]int, len(Counties))
    for i, c := range Counties {
        m[c] = i
    }
    return m
}()

// 获取地址的区县索引

func GetCountyIndexFromAddress(address string) int {
	// address: xx省xx市xx区xx路1号"

	var county string


	l := len(address)
	cityIndex := strings.Index(address, CityName)
	if cityIndex != -1 && (cityIndex+9) < l{
		address = address[cityIndex+9:]
		l = len(address)
		
		if districtIndex := strings.Index(address, "区"); districtIndex != -1 && (districtIndex+3) < l {
			county = address[:districtIndex+3]
		} else if districtIndex := strings.Index(address, "县"); districtIndex != -1 && (districtIndex+3) < l {
			county = address[:districtIndex+3]
		} else if districtIndex := strings.Index(address, "市"); districtIndex != -1 && (districtIndex+3) < l {
			county = address[:districtIndex+3]
		}
	}
	
	fmt.Println("county: " + county)
	// county = ""

	// 使用文本匹配的方式获取区县名称
	// 例如： xx区 或 xx市 或 xx县
	if county == "" {
		// 使用地址解析库，如果解析失败则使用地址中的区县名称
		locs := []string{
			address,
		}
		geoLocs := apc.GeoLocate(locs)
		// fmt.Println(fmt.Sprintf("%+v", geoLocs[0].County))
		// geoLocsJson, _ := json.Marshal(geoLocs)
		// fmt.Println(fmt.Sprintf("%+v", string(geoLocsJson)))

		if len(geoLocs) < 1 || geoLocs[0].County == "" {
			county = ""
		} else {
			county = geoLocs[0].County
		}

	}
	fmt.Println("county2: " + county)

	if i, e := CountyMap[county]; e {
		return i
	} else {
		return 0
	}
}